const express = require('express');
const pool = require('../utils/pool')
let router = express.Router();
router.get('/FuzzySearch',(req,res)=>{
	var obj= req.query
	let sql = 'select * from news'
	let params = []
	// 只有当title不为空时才添加模糊查询条件
	if(obj.title && obj.title.trim() !== '') {
		sql += ' where title LIKE ?'
		params.push(`%${obj.title}%`)
	}
	
	pool.query(sql, params, (x,y)=>{
		if(x){
			throw x
		}
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
	})
})
router.get('/allSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from news',(x,y)=>{
		if(x){
			throw x
		}
		// console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.post('/allAdd',(req,res)=>{
  let obj = req.body
  console.log(obj);
	pool.query('insert into news set ?',[obj],(x,y)=>{
		if(x){
			throw x;
		}
		console.log(y);
		res.send({code:200,msg:'注册成功'})
	})
 
});
router.get('/allDelete',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('delete from news where nid = ? ',[obj.nid],(x,y)=>{
		if(x){
			throw x
		}
		console.log(y);
		if(y.affectedRows===0){
			res.send({code:400,msg:'不存在'})
		}else{
			res.send({code:200,msg:'删除成功'})
		}
		
	})
	
})
router.get('/idSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from news where nid = ?',[obj.nid],(x,y)=>{
		if(x){
			throw x
		}
		// console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.post('/allUpdate',(req,res)=>{
	var obj = req.body
	console.log(obj);
	pool.query('update news set  ? where nid = ?',[obj,obj.nid],(x,y)=>{
		if(x){
			throw x
		}
		console.log(y);
		if(y.affectedRows===0){
			res.send({code:400,msg:'修改失败'})
		}else{
			res.send({code:200,msg:'修改成功',date:obj})
		}
		
	})
	
})
router.get('/nspeakAllSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from nspeak',(x,y)=>{
		if(x){
			throw x
		}
		// console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.get('/nspeakClassSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from nspeak where nid = ?',[obj.nid],(x,y)=>{
		if(x){
			throw x
		}
		// console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.post('/nspeakAllAdd',(req,res)=>{
  let obj = req.body
  console.log(obj);
	pool.query('insert into nspeak set ?',[obj],(x,y)=>{
		if(x){
			throw x;
		}
		console.log(y);
		res.send({code:200,msg:'注册成功'})
	})
 
});

module.exports=router;